package com.gopay.bis.manager.bank.ebank;

import java.util.Map;

import javax.annotation.Resource;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.TransUtil;
import com.gopay.bis.dao.payconfig.BisBankExtConfigDAO;
import com.gopay.common.Result;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.unionpay.ebank.UnionPayMessage;
import com.gopay.common.domain.bis.BaseBisBankExtConfig;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.MD5Util;
import com.gopay.remote.bank.BankManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;
/**
 * 民生银联对象封装
 * 
 * CuccPayManager.java
 * 
 * @author WangHongFei
 */
public class UnionPayManager implements BankManagerRemoteService {
	
	@Resource(name = "unionPayConfig")
	private Map<String, String> unionPayConfig;
	
	@Resource(name = "unionPayBankServiceClientHna")
	private BankService unionPayBankServiceClientHna;

	@Resource(name = "unionPayBankServiceClient")
	private BankService unionPayBankServiceClient;
	
	@Resource(name="bisBankExtConfigDAO")
	private BisBankExtConfigDAO bisBankExtConfigDAO;
	
		
	@Override
	public Object sign(BaseMessage msg) throws GopayException {
		// 获取银行接口通道配置信息
	    // 自动路由修改产品通道信息获取方式(根据产品、渠道、银行码获取) add by zhengxue
		BaseBisBankExtConfig bankConfig = bisBankExtConfigDAO.findExtConfigByBankChannelAndBankBusProd(msg.getBankBusProd(), msg.getBankIntrChann(), msg.getBank());
		msg.setBankOrderId("CP" + TransUtil.processOrderIdTo14Digit(msg.getOrderId()));
		//设置银联接口银行码
		msg.setSpecial2(bankConfig.getIntrfaceBankCode());
	    UnionPayMessage message = (UnionPayMessage)msg;
	    message.setVersion(unionPayConfig.get("CHINAPAY.VERSION"));
        message.setCharset(unionPayConfig.get("CHINAPAY.CHARSET"));
        message.setBankUrl(message.getPayUrl());
        message.setBackStagegateWay(unionPayConfig.get("TO.BANK.YINLIAN.BACKSTAGEGATEWAY"));
        message.setQueryUrl(unionPayConfig.get("TO.BANK.YINLIAN.QUERYURL"));
        message.setMerId(message.getMerID());
        message.setMerAbbr(unionPayConfig.get("CHINAPAY.MERABBR"));
        message.setFrontEndUrl(message.getPayNotifyUrl());
        message.setBackEndUrl(message.getPayRuturnUrl());
        message.setSignMethod(unionPayConfig.get("CHINAPAY.SIGNMETHOD"));
        message.setSecurityKey(message.getPrivateKeyPath());
        message.setAmount(message.getAmount().movePointRight(2));
        message.setUpTransType("01");
        message.setOrderCurrency("156");
        message.setCustomIp(message.getSpecial());
        String plainMessage = buildSignMessage(message);
        message.setPlainMessage(plainMessage);  
        if(message.isHna()){
            message.setSignMessage((String)unionPayBankServiceClientHna.sign(message));
        }else{
            message.setSignMessage((String)unionPayBankServiceClient.sign(message));  
        }
        BankLogUtils.printB2CManagerSignReturnLog(message);
        return message;
	}

	@Override
	public Object verify(BaseMessage msg) throws GopayException {		
		UnionPayMessage message = (UnionPayMessage)msg;
	    String plainMessage = buildVerifyPlain(message);
        message.setPlainMessage(plainMessage);
        BankLogUtils.printB2CManagerVerifySendLog(message);
        boolean flag;
        if(message.isHna()){
        	flag = (Boolean) unionPayBankServiceClientHna.verify(message);
        }else{
        	flag = (Boolean) unionPayBankServiceClient.verify(message);  
        }
        BankLogUtils.printB2CManagerVerifyReturnLog(message, flag);
        return flag;
	}

	@Override
	public Object query(Object obj) throws GopayException {
		UnionPayMessage message = (UnionPayMessage)obj;
		message.setVersion(unionPayConfig.get("CHINAPAY.VERSION"));
		message.setCharset(unionPayConfig.get("CHINAPAY.CHARSET"));
		message.setSignMethod(unionPayConfig.get("CHINAPAY.SIGNMETHOD"));
		message.setUpTransType("01");
		message.setMerId(message.getMerID());
		message.setSecurityKey(message.getPrivateKeyPath());
		message.setMerReserved("");
		message.setSignMessage(buildQueryMessage(message));
		BankLogUtils.printB2CManagerQuerySendLog(message, "");
		if(message.isHna()){
			message = (UnionPayMessage) unionPayBankServiceClientHna.query(message);
        }else{
        	message = (UnionPayMessage) unionPayBankServiceClient.query(message);
        }
        BankLogUtils.printB2CManagerQueryReturnLog(message);
		return message;
	}
	
    private String buildSignMessage(UnionPayMessage message) {
    	StringBuffer sb = new StringBuffer("");
        sb.append("acqCode=").append(message.getAcqCode());
        sb.append("&backEndUrl=").append(message.getBackEndUrl());
        sb.append("&charset=").append(message.getCharset());
        sb.append("&commodityDiscount=").append(message.getCommodityDiscount());
        sb.append("&commodityName=").append(message.getCommodityName());
        sb.append("&commodityQuantity=").append(message.getCommodityQuantity());
        sb.append("&commodityUnitPrice=").append(message.getCommodityUnitPrice());
        sb.append("&commodityUrl=").append(message.getCommodityUrl());
        sb.append("&customerIp=").append(message.getCustomIp());
        sb.append("&customerName=").append(message.getCustomerName());
        sb.append("&defaultBankNumber=").append(message.getDefaultBankNumber());
        sb.append("&defaultPayType=").append(message.getDefaultPayType());
        sb.append("&frontEndUrl=").append(message.getFrontEndUrl());
        sb.append("&merAbbr=").append(message.getMerAbbr());
        sb.append("&merCode=").append(message.getMerCode());
        sb.append("&merId=").append(message.getMerId());
        sb.append("&merReserved=").append(message.getMerReserved());
        sb.append("&orderAmount=").append(message.getAmount());
        sb.append("&orderCurrency=").append(message.getOrderCurrency());
        sb.append("&orderNumber=").append(message.getBankOrderId());
        sb.append("&orderTime=").append(message.getOrderDate());
        sb.append("&origQid=").append(message.getOrigQid());
        sb.append("&transTimeout=").append(message.getTransTimeout());
        sb.append("&transType=").append(message.getUpTransType());
        sb.append("&transferFee=").append(message.getTransferFee());
        sb.append("&version=").append(message.getVersion());
        sb.append("&").append(MD5Util.sign(message.getSecurityKey()));
        return sb.toString();
    }
    
    private String buildVerifyPlain(UnionPayMessage message) {
        StringBuffer sb = new StringBuffer();
        sb.append("charset=").append(message.getCharset()).append("&");
        sb.append("cupReserved=").append(message.getCupReserved()).append("&");
        sb.append("exchangeDate=").append(message.getExchangeDate()).append("&");
        sb.append("exchangeRate=").append(message.getExchangeRate()).append("&");
        sb.append("merAbbr=").append(message.getMerAbbr()).append("&");
        sb.append("merId=").append(message.getMerId()).append("&");
        sb.append("orderAmount=").append(message.getAmount().toString()).append("&");
        sb.append("orderCurrency=").append(message.getOrderCurrency()).append("&");
        sb.append("orderNumber=").append(message.getBankOrderId()).append("&");
        sb.append("qid=").append(message.getQid()).append("&");
        sb.append("respCode=").append(message.getRespCode()).append("&");
        sb.append("respMsg=").append(message.getRespMsg()).append("&");
        sb.append("respTime=").append(message.getRespTime()).append("&");
        sb.append("settleAmount=").append(message.getSettleAmount()).append("&");
        sb.append("settleCurrency=").append(message.getSettleCurrency()).append("&");
        sb.append("settleDate=").append(message.getSettleDate()).append("&");
        sb.append("traceNumber=").append(message.getTraceNumber()).append("&");
        sb.append("traceTime=").append(message.getTraceTime()).append("&");
        sb.append("transType=").append(message.getUpTransType()).append("&");
        sb.append("version=").append(message.getVersion()).append("&");
        sb.append(MD5Util.sign(unionPayConfig.get("CHINAPAY.SECURITYKEY")));
        return sb.toString();
    }

    private String buildQueryMessage(UnionPayMessage message) {
        StringBuffer signature = new StringBuffer();
        String md5SignSecureKey = MD5Util.sign(message.getSecurityKey());
        signature.append("charset=").append(message.getCharset()).append("&");
        signature.append("merId=").append(message.getMerId()).append("&");
        signature.append("merReserved=").append(message.getMerReserved()).append("&");
        signature.append("orderNumber=").append(message.getBankOrderId()).append("&");
        signature.append("orderTime=").append(message.getOrderDate()).append("&");
        signature.append("transType=").append(message.getUpTransType()).append("&");
        signature.append("version=").append(message.getVersion()).append("&");
        signature.append(md5SignSecureKey);
        return MD5Util.sign(signature.toString());
    }

	@Override
	public Object dayend(BaseMessage base) throws GopayException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object refund(BaseMessage base) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}
}
